package edu.columbia.cloudbox.ui;

import java.util.List;

import edu.columbia.cloudbox.CloudBoxActivity;
import edu.columbia.cloudbox.UserStatusService;
import edu.columbia.cloudbox.io.FileType;
import edu.columbia.cloudbox.io.LocalIO;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CachedFilesActivity extends ListActivity {

	private static final String LOG_TAG = "CachedFilesActivity";

	public static final String rootDir = UserStatusService.USER_NAME
			+ "_cache/" + UserStatusService.USER_NAME;

	public static List<FileType> files;

	@Override
	protected void onCreate(Bundle CachedInstanceState) {

		super.onCreate(CachedInstanceState);
		setBackButton();
		browse(rootDir, "");

	}

	@Override
	protected void onResume() {
		super.onResume();

		String path = FilePathOnTab
				.makePath(FilePathOnTab.currentPath_cachedFiles);

		setBackButton();
		browse(rootDir, path);

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.i(LOG_TAG, "Item clicked at " + position);

		super.onListItemClick(l, v, position, id);

		boolean isFolder = (Boolean) v.getTag();

		if (isFolder) {

			RelativeLayout layout = (RelativeLayout) v;
			TextView textView = (TextView) layout.getChildAt(1);
			String folderName = textView.getText().toString();
			// Update current path
			FilePathOnTab.currentPath_cachedFiles.push(folderName);
			String path = FilePathOnTab
					.makePath(FilePathOnTab.currentPath_cachedFiles);
			browse(rootDir, path);
		}
	}

	/**
	 * Display all files in local storage
	 * 
	 * @return
	 */
	private void browse(String userName, String path) {
		LocalIO localIO = UserStatusService.LocalIO_INSTANCE;
		if ("".equals(path)) {
			files = localIO.getFileTypesByFolder(userName);
			CloudBoxActivity.backButton.setVisibility(View.INVISIBLE);
		} else {
			files = localIO.getFileTypesByFolder(userName + path);
			CloudBoxActivity.backButton.setVisibility(View.VISIBLE);
		}

		CloudBoxActivity.pathTextView.setText(path);
		CachedFilesAdapter filesAdapter = new CachedFilesAdapter(this, files);
		filesAdapter.notifyDataSetChanged();
		setListAdapter(filesAdapter);
	}

	private void setBackButton() {
		CloudBoxActivity.backButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String backPath = FilePathOnTab
						.makeBackPath(FilePathOnTab.currentPath_cachedFiles);
				Log.i(LOG_TAG, "Back path: " + backPath);
				browse(rootDir, backPath);
			}

		});
	}
}
